package com.faithnmn.learnenglishbc.service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;

import android.app.Service;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

import com.faithnmn.learnenglishbc.R;
import com.faithnmn.learnenglishbc.db.DataBaseHelper;
import com.faithnmn.learnenglishbc.util.CommonUtil;
import com.faithnmn.learnenglishbc.util.Constants;
import com.faithnmn.utils.NotificationsHelper;
import com.faithnmn.utils.core.Core;
import com.faithnmn.utils.core.callbacks.GotConfigurationsCallback;
import com.faithnmn.utils.core.callbacks.GotNotificationsCallback;
import com.faithnmn.utils.core.model.Configurations;
import com.faithnmn.utils.core.model.Notification;
import com.faithnmn.utils.core.utils.receiver.NewInforAppsReceiver;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.MapBuilder;

public class InforService extends Service {
	public static long previousGettingData;
	public static DataBaseHelper dbHelper;
	public static InforService instance;
	private Core core;
	private static String CONFIGURATION_REQUEST_TAG = "cf_request_tag";
	private static String NOTIFICATION_REQUEST_TAG = "nt_request_tag";
	private static final int NOTIFICATION_ID = 1231;
	private SharedPreferences sharedPreferences;
	private NotificationsHelper notificationsHelper;
	private boolean isGettingNoti = false;
	@Override
	public void onCreate() {
		if(!CommonUtil.getSignature(this).equals(Constants.SIGNATURE)){
			EasyTracker.getInstance(this).send(MapBuilder.createEvent("Illegal operation detected", "Illegal operation detected:"+getPackageName(), com.faithnmn.utils.core.utils.Utils.getDeviceName(), Long.valueOf(1)).build());
			throw new RuntimeException("Illegal operation detected");
		}
		super.onCreate();
		instance = this;
		core =  Core.getInstance().init(this);
		sharedPreferences = getSharedPreferences("config_le", MODE_PRIVATE);
		doGetNotification();
	}

	private void doGetNotification() {
		if(isGettingNoti){
			return;
		}
		isGettingNoti = true;
		core.getConfigurations(CONFIGURATION_REQUEST_TAG, new GotConfigurationsCallback() {
			
			@Override
			public void onGotConfigurations(ArrayList<Configurations> configurations) {
				if(configurations == null){
					Log.e("BSXService","BSX got configurations NULL");
					isGettingNoti = false;
					return;
				}
				if(configurations.size() > 0){
					com.faithnmn.utils.core.utils.Utils.saveConfigurations(InforService.this, configurations, Constants.CACHE_CONFIGUATION_FILE);
					Intent noticeInforApps  = new Intent(NewInforAppsReceiver.NewInfoAppsAction);
					LocalBroadcastManager.getInstance(InforService.this).sendBroadcast(noticeInforApps);
				}
				for(int i=0;i<configurations.size();i++){
					Configurations config = configurations.get(i);
//					Log.e("appid","appid:"+config.udPId);
					if(config.udName.equals(getPackageName())){
//						Log.e(Constants.pkname,"pid:"+config.udPId);
						core.getNotifications(NOTIFICATION_REQUEST_TAG, config.udPId, "", new GotNotificationsCallback() {
							
							@Override
							public void onGotNotification(ArrayList<Notification> notifications) {
								isGettingNoti = false;
								if(notifications == null){
									Log.e("gotNotifications","gotNotification NULL!!!");
									return;
								}
								Log.e("gotNotifications","totalnoti:"+notifications.size());
								for(int i=0;i<notifications.size();i++){
									Log.e("gotNotifications","expires in:"+convertUnixtimeToDate(convertUnixtimeToDate(Long.parseLong(notifications.get(i).expireDate))));
									Log.e("gotNotifications",notifications.get(i).toString());
									String notified = sharedPreferences.getString("noti", "");
									if(!notified.contains(notifications.get(i).id)){
										notificationsHelper = new  NotificationsHelper(InforService.this, null, R.drawable.ic_launcher, R.drawable.ic_launcher, NOTIFICATION_ID);
										notificationsHelper.setBackgroundImageUrl(notifications.get(i).photoUrl).setClickNotificationUrl(notifications.get(i).link);
										String language = getResources().getConfiguration().locale.getLanguage();
										notificationsHelper.setAutoCancel(true).setTitle((TextUtils.isEmpty(language)|| !language.equalsIgnoreCase("vi"))?notifications.get(i).title_en:notifications.get(i).title);
										notificationsHelper.setContent((TextUtils.isEmpty(language)|| !language.equalsIgnoreCase("vi"))?notifications.get(i).content_en:notifications.get(i).content);
										if(TextUtils.isEmpty(notifications.get(i).photoUrl)){
											notificationsHelper.showNormalStyle();
										}else{
											Log.e("gotNotifications","photo:"+notifications.get(i).photoUrl);
											notificationsHelper.showBigPictureStyle();
										}
										sharedPreferences.edit().putString("noti", notified+","+notifications.get(i).id).commit();
										break;
									}
								}
							}
						});
						break;
					}
				}
			}
		});
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		if(intent!=null && intent.getAction()!=null && intent.getAction().equalsIgnoreCase("CH_NOTI")){
			// do subroutines here
            if(!isGettingNoti){
            	Log.e("Network Listener Temp", "Network Connected so do connect..");
            	doGetNotification();
            }
		}
		if(!CommonUtil.getSignature(this).equals(Constants.SIGNATURE)){
			EasyTracker.getInstance(this).send(MapBuilder.createEvent("Illegal operation detected", "Illegal operation detected:"+getPackageName(), com.faithnmn.utils.core.utils.Utils.getDeviceName(), Long.valueOf(1)).build());
			throw new RuntimeException("Illegal operation detected");
		}
		return START_STICKY;
	}
	
	public static InforService getInstance(){
		if(instance == null){
			instance = new InforService();
		}
		return instance;
	}
	
	public Date convertUnixtimeMilisecondToDate(long timeStamp){
		Date date = new java.util.Date((long)timeStamp*1000);
		return date ;
	}

	public Date convertUnixtimeToDate(long timeStamp){
		Date date = new java.util.Date((long)timeStamp);
		return date;
	}

	public String convertUnixtimeToDate(Date date){
		SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss dd-MM-yyyy"); 
//		sdf.setTimeZone(TimeZone.getTimeZone("GMT+7"));
		return sdf.format(date);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
}
